var categorian = {
  g_categorianDomain: 'user.adme.in',
  g_categorianHomepage: 'http://user.adme.in',
  g_userHomepage: '/blog',
  g_blogPath: '/blog/add',
  g_staggerPath: '/blog/stagger',
  g_queuePath: '/blog/queue',
  g_checkQueuePath: '/blog/dequeue',
  g_sendPath: '/blog/sendto',
  g_homePath: '/welcome/login',
  g_unreadPath: '/blog/nqueued',
  g_friendsPath: '/blog/friends',
  g_libraryPath: '/library/whatsnew',

  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById('categorian-strings');

    var appcontent = document.getElementById("appcontent");   // browser  
    if(appcontent) {
      appcontent.addEventListener("DOMContentLoaded", this.onPageLoad, true);
    }
    
    this.refreshInformation();
    window.setInterval(this.refreshInformation, 90*1000);
  },

  onPageLoad: function(aEvent) {  
    var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
    if (doc.location.hostname == categorian.g_categorianDomain) {
      if((doc.location.pathname == categorian.g_userHomepage) || (doc.location.pathname == categorian.g_queuePath)) {
        categorian.refreshInformation();
        // event listener for page unload
        // aEvent.originalTarget.defaultView.addEventListener("unload", function(event){ categorian.onPageUnload(event); }, true);
      }
    }
  }, 

  // preference functions
  get psvc() {
    return Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefService);
  },
  _get_branch: function(branch) {
    return this.psvc.getBranch(branch+'.');
  },
  getIntPref: function(b,prefName) {
    try {
      return this._get_branch(b).getIntPref(prefName);
    } catch(e) {
      Components.utils.reportError(e);
      return null;
    }
  },
  setIntPref: function(b,prefName, value) {
    try {
      this._get_branch(b).setIntPref(prefName, value);
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
  getCharPref: function(b,prefName) {
    try {
      return this._get_branch(b).getCharPref(prefName);
    } catch(e) {
      Components.utils.reportError(e);
      return null;
    }
  },
  setCharPref: function(b,prefName, value) {
    try {
      this._get_branch(b).setCharPref(prefName, value);
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
  getBoolPref: function(b,prefName) {
    try {
      return this._get_branch(b).getBoolPref(prefName);
    } catch(e) {
      Components.utils.reportError(e);
      return null;
    }
  },
  setBoolPref: function(b,prefName, value) {
    try {
      this._get_branch(b).setBoolPref(prefName, value);
    } catch(e) {
      Components.utils.reportError(e);
    }
  },
  getSettings: function(prefName) {
    if ((prefName == 'username') || (prefName == 'securitycode')) {
      var setting = this.getCharPref('extensions.categorian', prefName);
    }
    if (prefName == 'manuallogin') {
      var setting = this.getBoolPref('extensions.categorian', prefName);
    }
    return setting;
  },  
  // menu and button command functions
  toggleToolbar: function() {
    var categorianToolbar = document.getElementById('categorian-toolbar');
    categorianToolbar.collapsed = !categorianToolbar.collapsed;
  },
  onMenuItemCommand: function(event) {
    var username = this.getSettings('username');
    var securitycode = this.getSettings('securitycode');
    var manuallogin = this.getSettings('manuallogin');
    if (manuallogin == false) {
      var username = this.getSettings('username');
      var securitycode = this.getSettings('securitycode');
      if ((username == null) || (securitycode == null) || (username == '') || (securitycode == '')) {
        var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                      .getService(Components.interfaces.nsIPromptService);
        promptService.alert(window, this.strings.getString("alertTitle"),
                                    this.strings.getString("setPrefMessage"));
      }
      else {
        var url = this.g_categorianHomepage + '/blog/add'
                  + '?username=' + username
                  + '&access=' + securitycode + '&';
      }
    }
    else {
      var url = this.g_categorianHomepage + '/blog/add?';
    }
    url += 'img=' + encodeURIComponent(gContextMenu.mediaURL)
            + '&title=' + encodeURIComponent(content.document.title)
            + '&url=' + encodeURIComponent(content.location.href);
    openUILink(url, event, false, true);
  },
  toolbarEvent: function(event) {
    var targetURL = event.target.hasAttribute( 'targetURL' );
    if (targetURL) {
      var path = (event.target.getAttribute('targetURL'));
      var manuallogin = this.getSettings('manuallogin');
      if (manuallogin == false) {
        var username = this.getSettings('username');
        var securitycode = this.getSettings('securitycode');
        if ((username == null) || (securitycode == null) || (username == '') || (securitycode == '')) {
          var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                        .getService(Components.interfaces.nsIPromptService);
          promptService.alert(window, this.strings.getString("alertTitle"),
                                      this.strings.getString("setPrefMessage"));
        }
        else {
          var url = this.g_categorianHomepage + this[path]
                    + '?username=' + username
                    + '&access=' + securitycode + '&';
        }
      }
      else {
        if (this[path] == this.g_homePath) {
          var url = this.g_categorianHomepage + this.g_userHomepage;
        }
        else {
          var url = this.g_categorianHomepage + this[path] + '?';
        }
      }
      if ((this[path] == this.g_sendPath) || (this[path] == this.g_blogPath)) {
        url += 'title=' + encodeURIComponent(content.document.title) + '&url=' + encodeURIComponent(content.location.href);
      }
      openUILink(url, event, false, true);
      if (this[path] == this.g_checkQueuePath) {
        this.refreshInformation();
      }
    }
  },
  // refresh the message icon
  refreshInformation: function() {
    var selectedObject = document.getElementById('queueToolbarButton');
    var httpRequest = null;
    var manuallogin = categorian.getSettings('manuallogin');
    var pollUrl = categorian.g_categorianHomepage + categorian.g_unreadPath;
    if (manuallogin == false) {
      pollUrl += '?username='+ categorian.getCharPref('extensions.categorian', 'username')
              + '&access=' + categorian.getCharPref('extensions.categorian', 'securitycode');
    }
    //Application.console.log('start poll: ' + pollUrl);
    httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', pollUrl, true);
    httpRequest.onload = infoReceived;
    httpRequest.send(null);
    // set message icon to 'connecting' status
    selectedObject.setAttribute('class', 'queue-connecting');
    selectedObject.setAttribute('tooltiptext', 'Connecting');
    selectedObject.label = '';
      function infoReceived() {
        var output = httpRequest.responseText;
        if (output) {
          // parse and convert  
          //output.replace(/\W*$/, "");
          //output.replace(/(<([^>]+)>)/ig,"");
          var result = parseInt(output, 10);
          // do updates
          if (result == -1) {
            selectedObject.setAttribute('class', 'notloggedin');
            selectedObject.setAttribute('tooltiptext', 'You are not logged in');
            selectedObject.label = 'Click to log in';
          }
          if (result == 0) {
            selectedObject.setAttribute('class', 'queue-empty');
            selectedObject.setAttribute('tooltiptext', 'No new messages');
            selectedObject.label = '';
          }    
          if (result > 0) {
            selectedObject.setAttribute('class', 'queue-unread');
            selectedObject.setAttribute('tooltiptext', 'Click to see the next message');
            selectedObject.label = '(' + output + ')';
          }
        }
      };
  },
  // open a dialog window (used for info & settings)
  openDialog: function(url) {
    var strWindowFeatures = 'chrome,titlebar,toolbar,centerscreen,dialog=yes';
    window.openDialog(url, 'Categorian Firefox Extension', strWindowFeatures);  
  },
};
window.addEventListener("load", function () { categorian.onLoad(); }, false);
